/**
 * 疫苗查询页面JavaScript逻辑
 */

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    if (!Auth.isLoggedIn()) {
        window.location.href = '../login.html';
        return;
    }

    // 检查用户角色
    if (!Auth.checkRole(UserRole.NORMAL_USER)) {
        UI.showMessage('您没有权限访问此页面', 'danger');
        setTimeout(() => {
            Auth.logout();
        }, 2000);
        return;
    }

    // 初始化页面
    init();
});

/**
 * 初始化页面
 */
async function init() {
    // 显示用户信息
    displayUserInfo();
    
    // 加载疫苗列表
    await loadVaccineList();
}

/**
 * 显示用户信息
 */
function displayUserInfo() {
    const userInfo = Auth.getUserInfo();
    if (userInfo) {
        const userName = userInfo.account || '用户';
        document.getElementById('userName').textContent = userName;
        
        // 设置头像首字母
        const avatar = document.getElementById('userAvatar');
        avatar.textContent = userName.charAt(0).toUpperCase();
    }
}

/**
 * 加载疫苗列表
 */
async function loadVaccineList() {
    try {
        // 获取筛选条件
        const typeFilter = document.getElementById('vaccineTypeFilter').value;
        const nameFilter = document.getElementById('vaccineNameFilter').value.trim();

        // 构建查询参数
        const params = {};
        if (typeFilter !== '') {
            params.type = typeFilter;
        }

        // 获取疫苗列表（后端返回分页对象）
        const pageData = await HttpClient.get('/vaccine/list', params);

        // 从分页对象中提取疫苗数组
        let vaccines = pageData.records || [];

        // 如果有名称筛选，进行客户端过滤
        if (nameFilter) {
            vaccines = vaccines.filter(vaccine =>
                vaccine.name && vaccine.name.toLowerCase().includes(nameFilter.toLowerCase())
            );
        }

        // 显示疫苗列表
        displayVaccines(vaccines);
    } catch (error) {
        console.error('加载疫苗列表失败:', error);
        UI.showMessage('加载疫苗列表失败', 'danger');
    }
}

/**
 * 显示疫苗列表
 */
function displayVaccines(vaccines) {
    const grid = document.getElementById('vaccineGrid');
    grid.innerHTML = '';
    
    if (!vaccines || vaccines.length === 0) {
        grid.innerHTML = `
            <div class="empty-state" style="grid-column: 1 / -1;">
                <i class="fas fa-vial"></i>
                <p>暂无疫苗信息</p>
            </div>
        `;
        return;
    }
    
    vaccines.forEach(vaccine => {
        const card = createVaccineCard(vaccine);
        grid.appendChild(card);
    });
}

/**
 * 创建疫苗卡片
 */
function createVaccineCard(vaccine) {
    const card = document.createElement('div');
    card.className = 'vaccine-card';
    
    // 根据疫苗类型选择图标
    const iconMap = {
        0: 'fa-vial',           // 普通疫苗
        1: 'fa-baby',           // 儿童疫苗
        2: 'fa-user-shield'     // 成人疫苗
    };
    const icon = iconMap[vaccine.type] || 'fa-syringe';
    
    card.innerHTML = `
        <div class="vaccine-card-header">
            <div class="vaccine-icon">
                <i class="fas ${icon}"></i>
            </div>
            <div class="vaccine-title">
                <h4>${vaccine.name || '未知疫苗'}</h4>
                <p>
                    <span class="badge badge-info">${Format.vaccineType(vaccine.type)}</span>
                </p>
            </div>
        </div>
        <div class="vaccine-info">
            <div class="vaccine-info-item">
                <span class="vaccine-info-label">生产厂家</span>
                <span class="vaccine-info-value">${vaccine.manufacturer || '-'}</span>
            </div>
            <div class="vaccine-info-item">
                <span class="vaccine-info-label">批准文号</span>
                <span class="vaccine-info-value">${vaccine.approvalNumber || '-'}</span>
            </div>
            <div class="vaccine-info-item">
                <span class="vaccine-info-label">疫苗类型</span>
                <span class="vaccine-info-value">${Format.vaccineType(vaccine.type)}</span>
            </div>
        </div>
        <div class="vaccine-actions">
            <button class="btn btn-primary btn-sm" style="width: 100%;" onclick="goToAppointment()">
                <i class="fas fa-calendar-plus"></i> 立即预约
            </button>
        </div>
    `;
    
    return card;
}

/**
 * 跳转到预约页面
 */
function goToAppointment() {
    window.location.href = 'appointment.html';
}

/**
 * 退出登录
 */
function handleLogout() {
    UI.confirm('确定要退出登录吗？', () => {
        Auth.logout();
    });
}

